/**
 * @desc: 快递授权
 * @author: binlety
 */
import React, { useState, useEffect, useMemo } from 'react';
import { Modal, message } from 'antd';
import CommonTab from '@/components/CommonTab';
import FormRender from '@/components/FormRender';
import OperaBtnRender from '@/components/OperaBtnRender';
import SyncSurfaceModal from './component/SyncSurfaceModal.jsx';
import JdSyncModal from './component/JdSyncModal.jsx';
import AddSFModal from './component/AddSFModal.jsx';
import FastRabbitModal from './component/FastRabbitModal.jsx';
import OtherTableList from './component/OtherTableList.jsx';
import ZjfTableList from './component/ZjfTableList.jsx';
import { useResize } from '@/hooks/useResize';
import { getFormItem, tabArr, storeMap } from './config.js';
import {
  getTableListOp,
  getZjfTableListOp,
  getBaseExpressListOp,
  queryShopList,
  getJdStoreListOp,
  delSfOp,
  deleteJituOp,
  getJituPageOp,
  queryJitufacebill,
} from './service.js';

const ExpressAuth = () => {
  const [type, setType] = useState('1'); //tab状态
  const [query, setQuery] = useState({}); //表单参数
  const [data, setData] = useState([]); //表格数据
  const [pages, setPages] = useState({
    current: 1,
    total: 0,
    pageSize: 10,
  });
  const [shopList, setShopList] = useState([]); //网店
  const [sfStoreId, setSfStoreId] = useState(''); //当前顺丰店铺id
  const [jtVisible, setJtVisible] = useState(''); //是否打开极兔快递的弹窗
  const [record, setRecord] = useState({}); //单行的数据
  const [selectedRowKeys, setSelectedRowKeys] = useState(); // 极兔快递的单选数据
  const [visible, setVisible] = useState(0); //1.同步
  const [expressList, setExpressList] = useState([]);

  //表单数据
  const formArr = useMemo(() => {
    return getFormItem({
      expressId: expressList,
      ecstoreId: shopList,
    }, type);
  }, [expressList, shopList, type])

  //监听变更
  const { el: headerEl, height: headerHeight } = useResize();

  useEffect(() => {
    getBaseExpressList(); //获取基础快递列表
  }, []);

  useEffect(() => {
    if (['1', '2', '4', '8', '14', '15', '25', '26', '40'].includes(type)) {
      getShopList(); //网店
    } else if (type == 3) {
      getJdShoplist();
    }
  }, [type]);

  useEffect(() => {
    getTableList(); //获取表格数据
  }, [pages]);

  //快递公司列表
  const getBaseExpressList = async () => {
    const { success, data } = await getBaseExpressListOp();
    if (success) {
      const arr = [];
      data.map(v => {
        arr.push({
          label: v.name,
          value: v.id
        })
      })
      setExpressList(arr);
    }
  };

  //网店列表
  const getShopList = async () => {
    const { success, data = [] } = await queryShopList({
      type: storeMap[type],
    });
    if (success) {
      setShopList(data);
    } else {
      setShopList([]);
    }
  };

  //京东店铺
  const getJdShoplist = async () => {
    const { success, data = [] } = await getJdStoreListOp();
    if (success) {
      const arr = data.map((item) => {
        return {
          ...item,
          storeName: item.ecstoreName,
        };
      });
      setShopList(arr);
    } else {
      setShopList([]);
    }
  };

  //获取表格数据
  const getTableList = async () => {
    START_LOADING();
    if (type == '6') {
      const { success, data } = await getZjfTableListOp({
        ...query,
      });
      if (success) {
        setData(data);
      }
    } else if (type == '28') {
      const { success, data } = await getJituPageOp({
        ...query,
        platform: type,
        size: pages.pageSize,
        current: pages.current,
      });
      if (success) {
        const { records, total } = data;
        setData(records);
        pages.total = total;
        setPages(pages);
      }
    } else {
      const { success, data } = await getTableListOp({
        ...query,
        platform: type,
        size: pages.pageSize,
        current: pages.current,
      });
      if (success) {
        const { records, total } = data;
        setData(records);
        pages.total = total;
        setPages(pages);
      }
    }
    END_LOADING();
  };

  //Tab区
  const TabProps = {
    type,
    data: tabArr,
    onChange(type) {
      setData([]);
      setType(type);
      setQuery({});
      setPages({ ...pages, current: 1, total: 0 });
    },
  };

  //表单渲染组件
  const FormRenderProps = {
    key: type,
    query,
    formArr,
    formConfig: {
      name: 'express-config-form',
      style: { marginBottom: '16px' }
    },
    clickSearch(val) {
      setQuery(val);
      setPages({
        ...pages,
        current: 1
      })
    },
    clickReset() {
      setQuery({});
      setPages({
        ...pages,
        current: 1
      })
    },
  }

  //列表（三方平台）
  const OtherTableProps = {
    type,
    data,
    pages,
    setPages,
    headerHeight,
    selectedRowKeys,
    updateFunc(id, record) {
      if (type == '28') {
        // 极兔快递的编辑
        setRecord(record);
        setJtVisible(true);
      } else {
        setSfStoreId(id);
      }
    },
    deleteOperator(id) {
      deleteSfAuth(id);
    },
    handleSelectRowKey(item) {
      // 极兔快递的单个勾选
      setSelectedRowKeys(item);
    },
    refreshTableList() {
      setPages({ ...pages });
    }
  };

  //表格（找家纺）
  const ZjfListProps = {
    headerHeight,
    data,
    handleUpdateTable() {
      getTableList();
    },
  };

  //分页区
  const pageProps = {
    pages,
    handleChange(current, size) {
      setPages({
        ...pages,
        current: current == pages.current ? 1 : current,
        pageSize: size,
      });
    },
  };

  // button
  const handleClick = () => {
    if (type == 3) {
      //京东
      if (shopList.length) {
        setVisible(2);
      } else {
        Modal.info({ content: '当前无需要同步面单的网店' });
      }
    } else if (type == 5) {
      //新增顺丰面单授权
      setSfStoreId('add');
    } else if (type == 28) {
      //新增极兔面单授权
      setJtVisible(true);
    } else {
      const time_num = new Date().getTime();
      const arr = shopList.filter(
        (item) => item.authExpireTime && item.authExpireTime * 1000 > time_num
      );
      if (arr.length) {
        setVisible(1);
      } else {
        Modal.info({ content: '当前无需要同步面单的网店' });
      }
    }
  };

  //删除顺丰授权
  const deleteSfAuth = async (id) => {
    START_LOADING();
    let deleteItem = delSfOp;
    if (type == '28') {
      //删除极兔快递
      deleteItem = deleteJituOp;
    }
    const { msg, success } = await deleteItem({ id });
    if (success) {
      setPages({
        ...pages,
        current: 1,
      });
      message.success(msg);
    }
    END_LOADING();
  };

  //同步剩余单号
  const handSynchro = async () => {
    if (selectedRowKeys) {
      START_LOADING();
      const { msg, success } = await queryJitufacebill({
        id: selectedRowKeys,
      });
      if (success) {
        setPages({
          ...pages,
          current: 1,
        });
        message.success(msg);
      }
      END_LOADING();
    } else {
      message.info('请选择需要操作的网点！');
    }
  };

  //公共授权同步弹窗
  const SyncSurfaceModalProps = {
    type,
    shopList,
    visible: visible == 1,
    handleOk() {
      setPages({ ...pages }); //更新table
      // getShopList();//更新网店
    },
    handleCancel() {
      setVisible(0);
    },
  };

  //京东授权
  const JdSyncModalProps = {
    shopList,
    visible: visible == 2,
    handleOk() {
      setPages({ ...pages }); //更新table
      getJdShoplist(); //更新网店
    },
    handleCancel() {
      setVisible(0);
    },
  };

  //顺丰授权
  const AddSFModalProps = {
    visible: sfStoreId,
    handleOk() {
      setPages({
        ...pages,
        current: 1,
      });
    },
    handleCancel() {
      setSfStoreId('');
    },
  };

  //极兔授权
  const FastRabbitModalProps = {
    visible: jtVisible,
    record,
    handleOk() {
      setPages({
        ...pages,
        current: 1,
      });
    },
    handleCancel() {
      setJtVisible(false);
      setRecord({});
    },
  };

  //操作按钮
  const btnArr = type == '28' ?
    [
      { elType: 'button', text: '新增极兔面单授权', onClick: handleClick },
      { elType: 'button', text: '同步剩余单号', onClick: handSynchro }
    ]
    :
    [
      { elType: 'button', text: type == '5' ? '新增顺丰面单授权' : '同步已开通的电子面单服务', onClick: handleClick },
    ]

  return (
    <>
      <CommonTab {...TabProps} />
      <div ref={headerEl}>
        <FormRender {...FormRenderProps} />
      </div>
      <div className='global-page-wrap'>
        {
          type == '6' ?
            <ZjfTableList {...ZjfListProps} />
            : (
              <>
                <OperaBtnRender style={{ marginBottom: '12px' }} btnArr={btnArr} />
                <OtherTableList {...OtherTableProps} />
              </>
        )}
      </div>
      {/* 同步面单弹窗 */}
      <SyncSurfaceModal {...SyncSurfaceModalProps} />
      {/* 京东授权 */}
      <JdSyncModal {...JdSyncModalProps} />
      {/* 添加顺丰授权弹窗 */}
      <AddSFModal {...AddSFModalProps} />
      {/* 添加极兔授权弹窗 */}
      <FastRabbitModal {...FastRabbitModalProps} />
    </>
  );
};

// export default ExpressAuth
export default ExpressAuth;